package com.redwine.app;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.redwine.app.chat.ChatHelper;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.model.User;
import com.redwine.app.net.responses.LoginResponse;
import com.redwine.app.utils.ActivitySplitAnimationUtil;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.LogUtil;
import com.redwine.app.utils.NetUtil;
import com.redwine.app.utils.Settings;
import com.redwine.app.utils.Utils;

import java.util.LinkedHashMap;
import java.util.Map;

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    @ViewInject(R.id.login_et_user)
    private EditText loginEtUser;
    @ViewInject(R.id.login_et_password)
    private EditText loginEtPassword;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_main);
        ViewUtils.inject(this);
    }


    @OnClick({R.id.login_bt, R.id.login_tv_forget_password, R.id.login_tv_register})
    public void mClick(View v) {
        switch (v.getId()) {
            case R.id.login_bt:
                submit();
                break;
            case R.id.login_tv_forget_password:
                intent = new Intent(LoginActivity.this, LoginRegisterActivity.class);
                intent.putExtra(LoginRegisterActivity.IS_REGISTERED, false);
                startActivity(intent);
                break;
            case R.id.login_tv_register:
                intent = new Intent(LoginActivity.this, LoginRegisterActivity.class);
                intent.putExtra(LoginRegisterActivity.IS_REGISTERED, true);
                startActivity(intent);
                break;
        }
    }

    private void submit() {
        // validate
        String user = loginEtUser.getText().toString().trim();
        if (TextUtils.isEmpty(user)) {
            Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String password = loginEtPassword.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }



        if (!NetUtil.checkNet(this)) {
            Utils.showToast(R.string.generic_check);
            return;
        }

        requestLoginData(user, password);

    }

    /**
     * 登陆
     * 作者：gassion on 17/8/17 00:19
     * 最可怕的敌人，就是没有坚强的信念。
     */
    protected void requestLoginData(String user, String password) {
        showWaiting();
        String url = NetworkConstants.LOGIN_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("mobile", user);
        params.put("password", password);
        GsonRequest<LoginResponse> request = new GsonRequest<>(url, Request.Method.POST,
                LoginResponse.class, false, params, new Response.Listener<LoginResponse>() {
            @Override
            public void onResponse(LoginResponse response) {
                if (response.isSuccess()) {
                    if (!ChatHelper.getInstance().isLoggedIn()) {
                        LogUtil.e("params", "huanxin");
                        register(response);
                    } else {
                        dismissWaiting();
                        LogUtil.e("params", "logIntomain");
                        skipMainActivity(response);
                    }
                } else {
                    Utils.showToast(response.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                Utils.showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 跳转到主页
     *
     * @param response 登陆成功的bean
     */
    public void skipMainActivity(LoginResponse response) {
        /**
         * 设置用户名昵称和头像
         */
        final User responseData = response.getData();
        ChatHelper.getInstance().getUserProfileManager().setCurrentUserNick(responseData.getNickname());
        ChatHelper.getInstance().setCurrentUserName(responseData.getUid());
        ChatHelper.getInstance().getUserProfileManager().setCurrentUserAvatar(responseData.getAvatar());
        Gson gson = new Gson();
        String json = gson.toJson(responseData);
        LogUtil.e("params", "logIn" + json);
        Settings.saveProfile(json);//
        Settings.setSharedPreferences(Settings.SUPPLIER_STATUS, responseData.getSupplier_status());
        Settings.setSharedPreferences(Settings.BUYER_STATUS, responseData.getBuyer_status());

        Global.setUser(json); //保存登录信息
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        ActivitySplitAnimationUtil.startActivity(LoginActivity.this, intent);
        finish();
        overridePendingTransition(0, R.anim.base_slide_right_out);
    }

    public void register(final LoginResponse response) {
        final User responseData = response.getData();
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMClient.getInstance().createAccount(responseData.getUid(), "123456");
                    runOnUiThread(new Runnable() {
                        public void run() {
                            LogUtil.e("gassion", responseData.getUid() + "=========正常登陆");
                            loginChat(response);
                        }
                    });
                } catch (final HyphenateException e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            LogUtil.e("gassion", response.getData().getUid() + "=========异常登陆");
                            loginChat(response);
                        }
                    });
                }
            }
        }).start();
    }

    public void loginChat(final LoginResponse response) {
        EMClient.getInstance().login(response.getData().getUid(), "123456", new EMCallBack() {

            @Override
            public void onSuccess() {
                dismissWaiting();
                LogUtil.e("gassion", response.getData().getUid() + "=========登陆成功");
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                skipMainActivity(response);
            }

            @Override
            public void onProgress(int progress, String status) {
                dismissWaiting();
                LogUtil.e("gassion", "=========1错误" + status);
            }

            @Override
            public void onError(final int code, final String message) {
                dismissWaiting();
                LogUtil.e("gassion", "=========2错误" + message);
            }
        });
    }
}
